package cn.com.dbappsecurity.frame.paramparse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.dbappsecurity.frame.annotations.Validate;
import cn.com.dbappsecurity.frame.exception.FrameException;

public class ParamLong implements IParamParse{

	private String name;
	private Validate validate;
	private boolean array;
	
	public ParamLong(String name,boolean array,Validate validate){
		this.name = name;
		this.array = array;
		this.validate = validate;
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String[] values = request.getParameterValues(name);
		if(values == null){
			values = new String[0];
		}
		Long[] value = new Long[values.length];
		for(int i=0;i<values.length;i++){
			try {
				value[i] = Long.parseLong(values[i].trim());
			} catch (Exception e) {
				LOG.error("参数解析出错",e);
			}
		}
		if(!validate(value)){
			throw new FrameException(FrameException.TYPE_ARGU_ERROR);
		}
		setDefValue(value);
		return array ? value : (value.length == 0 ? 0 : value[0]);
	}

	private void setDefValue(Long[] value){
		if(value != null){
			for(int i=0;i<value.length;i++){
				if(value[i] == null){
					value[i] = 0L;
				}
			}
		}
	}
	
	private boolean validate(Long[] value) {
		if(validate != null){
			if(validate.required() && value.length == 0){
				return false;
			}
			for(Long val : value){
				if(validate.required() && val == null){
					return false;
				}
				double minLen = validate.minLen();
				if(minLen != -1){
					if(val < minLen){
						return false;
					}
				}
				double maxLen = validate.maxLen();
				if(maxLen != -1){
					if(val > maxLen){
						return false;
					}
				}
			}
		}
		return true;
	}
	
}
